package base;

import config.ApiConfig;
import lombok.extern.slf4j.Slf4j;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import org.testng.Assert;
import org.yaml.snakeyaml.Yaml;
import utils.HttpUtils;
import utils.JsonUtils;

import static base.BaseTest.getPlaceholderValue;
import static base.PlaceholderResolver.*;

@Slf4j
public class HttpRequestExecutor {
    // 执行单个请求并返回结果
    public static String executeRequest(ApiConfig config) {
        try {
            String url = config.getHost() + config.getPath();
            String response;
            switch(config.getMethod().toUpperCase()) {
                case "GET":
                    log.debug("url: {}", url);
                    log.debug("Request-header: {}", config.getHeaders());
                    response = HttpUtils.sendGet(url, config.getParameters(), config.getHeaders());
                    log.debug("Response: {}", response);
                    return response;
                case "POST":
                    log.debug("url: {}", url);
                    log.debug("Request-header: {}", config.getHeaders());
                    log.debug("Request-body: {}", config.getBody());
                    response = HttpUtils.sendPost(url, config.getBody(), config.getHeaders());
                    log.debug("Response: {}", response);
                    return response;
                // 添加其他HTTP方法支持
                default:
                    throw new IllegalArgumentException("Unsupported method: " + config.getMethod());
            }
        } catch (Exception e) {
            // 记录异常日志
            log.error("Error executing HTTP request");
            throw new RuntimeException("Failed to execute HTTP request", e);
        }
    }

    // 执行多个请求并返回结果列表
    public static List<String> executeMultipleRequests(List<ApiConfig> configs) {
        return configs.stream()
                .map(HttpRequestExecutor::executeRequest)
                .collect(java.util.stream.Collectors.toList());
    }

    // 加载单个YAML文件
    public static ApiConfig loadYamlSingle(String configFile) {
        Yaml yaml = new Yaml();
        InputStream inputStream = HttpRequestExecutor.class
                .getClassLoader()
                .getResourceAsStream(configFile);

        if (inputStream == null) {
            throw new RuntimeException("YAML file not found: " + configFile);
        }

        try {
            Map<String, Object> data = yaml.load(inputStream);
            // 使用 mapToApiConfig 转换
            ApiConfig config = mapToApiConfig(data);

            // 检查必要字段是否为空
            if (config == null) {
                throw new RuntimeException("Failed to load API configuration from YAML");
            }
            return config;
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }

    // 加载多个YAML文件
    public static List<ApiConfig> loadYamlMulti(String configFile) {
        Yaml yaml = new Yaml();
        InputStream inputStream = HttpRequestExecutor.class
                .getClassLoader()
                .getResourceAsStream(configFile);

        if (inputStream == null) {
            throw new RuntimeException("YAML file not found: " + configFile);
        }

        try {
            // 加载为Map格式以判断结构
            Map<String, Object> data = yaml.load(inputStream);
            // 处理多个请求的情况 - 简化映射过程
            List<Map<String, Object>> requestList = (List<Map<String, Object>>) data.get("requests");

            List<ApiConfig> configs = requestList.stream()
                    .map(PlaceholderResolver::mapToApiConfig)
                    .collect(java.util.stream.Collectors.toList());

            return configs;
        } catch (Exception e) {
            log.error("Failed to load multi-request YAML");
            throw new RuntimeException(e.getMessage(), e);
        }
    }






}